package com.hzxy.yiyid.web.module.service.impl;

import com.hzxy.yiyid.web.common.base.BaseResult;
import com.hzxy.yiyid.web.common.error.ErrorCodeEnum;
import com.hzxy.yiyid.web.module.cache.MedicineDataCache;
import com.hzxy.yiyid.web.module.controller.vo.*;
import com.hzxy.yiyid.web.module.repository.MedicareDrugDoRepository;
import com.hzxy.yiyid.web.module.repository.MedicineDoRepository;
import com.hzxy.yiyid.web.module.repository.SubstandardDrugDoRepository;
import com.hzxy.yiyid.web.module.repository.entity.DiseaseDo;
import com.hzxy.yiyid.web.module.repository.entity.MedicineDo;
import com.hzxy.yiyid.web.module.service.DrugService;
import com.hzxy.yiyid.web.module.utils.wordFilter.WordFilter;
import com.hzxy.yiyid.web.tool.xunfei.WebOCR;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.TextWatermark;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.documents.WatermarkLayout;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.awt.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ClassName DrugServiceImpl
 * @Description TOOD
 * @Author RAICOM2023
 * @Date 2023/3/6 22:40
 * @Version 1.0
 **/
@Service(value = "drugService")
@Configuration
@Transactional
public class DrugServiceImpl implements DrugService {

    private static final Logger logger = LoggerFactory.getLogger(DrugServiceImpl.class);

    @Autowired
    private EntityManager em;

    @Resource
    private MedicareDrugDoRepository medicareDrugDoRepository;

    @Resource
    private SubstandardDrugDoRepository substandardDrugDoRepository;

    @Resource
    private MedicineDoRepository medicineDoRepository;

    @Resource
    private MedicineDataCache medicineDataCache;

    @Resource
    private WordFilter wordFilter;

    @Value("${server.port}")
    private String port;

    @Value("${pic.ip}")
    private String ip;
    /*
     * @Author RAICOM2023
     * @Description //根据药品名称查询不合规药品
     * @Date 22:41 2023/3/6
     * @Param [drugRequestVO]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    @Override
    public List<Map<String, Object>> listSubstandardDrug(DrugRequestVO drugRequestVO) throws Exception {
        List<Map<String, Object>> substandardDrugMapList = new ArrayList<>();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select * from substandard_drug where 1 = 1 ");
        if(StringUtils.isNotEmpty(drugRequestVO.getYpmc())) {
            sqlStr.append("and ypmc like '%" + drugRequestVO.getYpmc().trim() + "%'");
        }
        if(StringUtils.isNotEmpty(drugRequestVO.getScdw())) {
            sqlStr.append("and scdw like '%" + drugRequestVO.getScdw().trim() + "%'");
        }
        if(StringUtils.isNotEmpty(drugRequestVO.getJyjg())) {
            sqlStr.append("and jyjg like '%" + drugRequestVO.getJyjg().trim() + "%'");
        }
        if(StringUtils.isNotEmpty(drugRequestVO.getJply())) {
            sqlStr.append("and jyly like '%" + drugRequestVO.getJply().trim() + "%'");
        }
        if(StringUtils.isNotEmpty(drugRequestVO.getJply())) {
            sqlStr.append("and jply like '%" + drugRequestVO.getJply().trim() + "%'");
        }
        Integer startIndex = (drugRequestVO.getPageNo() - 1) * drugRequestVO.getPageSize();
        //plgresql分页SQL
        /*sqlStr.append(
                " order by id asc limit '" + drugRequestVO.getPageSize() + "' "
                        + "offset '"
                        + startIndex + "'");*/
        //MySQL分页SQL
        sqlStr.append(
                " order by scdw asc limit " + drugRequestVO.getPageSize() + " offset " + startIndex + "");
        String sql = sqlStr.toString();

        logger.info("不合格药品查询SQL：" + sql);
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<?> rows = query.getResultList();
        if(CollectionUtils.isEmpty(rows)){
            return substandardDrugMapList;
        }else{
            for(Object obj : rows){
                Map<String, String> hashMap = new LinkedHashMap<>();
                Map<Object, Object> map = (Map)obj;
                for (Object key : map.keySet()) {
                    if (null == map.get(key) || "".equals(map.get(key).toString())) {
                        hashMap.put(key.toString().toUpperCase(), null);
                    } else {
                        hashMap.put(key.toString().toUpperCase(), map.get(key).toString());
                    }
                }
                Map<String, Object> substandardDrugMap = new HashMap<>();
                substandardDrugMap.put("id", hashMap.get("ID"));
                substandardDrugMap.put("scdw", hashMap.get("SCDW"));
                substandardDrugMap.put("xmmc", hashMap.get("XMMC"));
                substandardDrugMap.put("ypmc", hashMap.get("YPMC"));
                substandardDrugMap.put("bhgxm", hashMap.get("BHGXM"));
                substandardDrugMap.put("jyjg", hashMap.get("JYJG"));
                substandardDrugMap.put("jyyj", hashMap.get("JYYJ"));
                substandardDrugMap.put("jply", hashMap.get("JPLY"));
                substandardDrugMap.put("jcjg", hashMap.get("JCJG"));
                substandardDrugMapList.add(substandardDrugMap);
            }
        }
        em.close();
        return substandardDrugMapList;
    }

    /*
     * @Author RAICOM2023
     * @Description //根据药品名称查询不合规药品--总数
     * @Date 22:41 2023/3/6
     * @Param [drugRequestVO]
     * @return long
     **/
    @Override
    public long findSubstandardDrugTotal(DrugRequestVO drugRequestVO) throws Exception {
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select count(*) from substandard_drug where 1 = 1 ");
        sqlStr.append("and ypmc like '%" + drugRequestVO.getYpmc() + "%'");
        String sql = sqlStr.toString();
        Query query = em.createNativeQuery(sql);
        Object o = query.getSingleResult();
        em.close();
        if(o == null){
            return 0L;
        }else{
            BigInteger big = (BigInteger) o;
            return big.longValue();
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //根据药品名称查询是否是医保药品
     * @Date 12:38 2023/3/6
     * @Param [drugRequestVO]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    @Override
    public List<Map<String, Object>> listMedicareDrug(DrugRequestVO drugRequestVO) throws Exception {
        List<Map<String, Object>> medicareDrugMapList = new ArrayList<>();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select * from medicare_drug where 1 = 1 ");
        sqlStr.append("and ( tym like '%" + drugRequestVO.getTym() + "%' or spm like '%"+ drugRequestVO.getTym() + "%' )");
        Integer startIndex = (drugRequestVO.getPageNo() - 1) * drugRequestVO.getPageSize();
        //postgresql分页SQL
        /*sqlStr.append(
                "order by id asc limit '" + drugRequestVO.getPageSize() + "' "
                        + "offset '"
                        + startIndex + "'");*/
        //MySQL分页SQL
        sqlStr.append(
                " order by id asc limit " + drugRequestVO.getPageSize() + " offset " + startIndex + "");
        String sql = sqlStr.toString();
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<?> rows = query.getResultList();
        if(CollectionUtils.isEmpty(rows)){
            return medicareDrugMapList;
        }else{
            for(Object obj : rows){
                Map<String, String> hashMap = new LinkedHashMap<>();
                Map<Object, Object> map = (Map)obj;
                for (Object key : map.keySet()) {
                    if (null == map.get(key) || "".equals(map.get(key).toString())) {
                        hashMap.put(key.toString().toUpperCase(), null);
                    } else {
                        hashMap.put(key.toString().toUpperCase(), map.get(key).toString());
                    }
                }
                Map<String, Object> medicareDrugMap = new HashMap<>();
                medicareDrugMap.put("id", hashMap.get("ID"));
                medicareDrugMap.put("gg", hashMap.get("GG"));
                medicareDrugMap.put("spm", hashMap.get("SPM"));
                medicareDrugMap.put("bzcz", hashMap.get("BZCZ"));
                medicareDrugMap.put("dw", hashMap.get("DW"));
                medicareDrugMap.put("zj", hashMap.get("ZJ"));
                medicareDrugMap.put("zhb", hashMap.get("ZHB"));
                medicareDrugMap.put("bz", hashMap.get("BZ"));
                medicareDrugMap.put("tym", hashMap.get("TYM"));
                medicareDrugMap.put("scqy", hashMap.get("SCQY"));
                medicareDrugMap.put("jx", hashMap.get("JX"));
                medicareDrugMapList.add(medicareDrugMap);
            }
        }
        em.close();
        return medicareDrugMapList;
    }

    /*
     * @Author RAICOM2023
     * @Description //根据药品名称查询是否是医保药品--总个数
     * @Date 12:39 2023/3/6
     * @Param [drugRequestVO]
     * @return long
     **/
    @Override
    public long findMedicareDrugTotal(DrugRequestVO drugRequestVO) throws Exception {
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select count(*) from medicare_drug where 1 = 1 ");
        sqlStr.append("and ( tym like '%" + drugRequestVO.getTym() + "%' or spm like '%"+ drugRequestVO.getTym() + "%' )");
        String sql = sqlStr.toString();
        Query query = em.createNativeQuery(sql);
        Object o = query.getSingleResult();
        em.close();
        if(o == null){
            return 0L;
        }else{
            BigInteger big = (BigInteger) o;
            return big.longValue();
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //识别药物说明书
     * @Date 13:17 2023/3/6
     * @Param [file]
     * @return com.hzxy.yiyid.web.common.base.BaseResult<?>
     **/
    @Override
    public BaseResult<?> aiDrug(MultipartFile file) throws Exception {
        //String text = BaiduInfoConverter.getOcrString(BaiduAI.BASIC(file.getBytes()));
        List<String> ocrList = WebOCR.OCR(file.getBytes());
        DrugVO drugVO = new DrugVO();
        int isCf = 1;
        for(String str : ocrList){
            if(str.contains("【通用名称】") || str.contains("【药品名称】")|| str.contains("*【药品名称】")|| str.contains("药品名称】")){
                drugVO.setMc(str.split("：")[1]);
            }else if(str.contains("【成份】") || str.contains("【成    份】")|| str.contains("【成    份】")){
                drugVO.setCf(str.split("】")[1]);
            }else if(str.contains("【性状】") || str.contains("【性   状】")|| str.contains("【性   状】")){
                drugVO.setXz(str.split("】")[1]);
            }else if(str.contains("【功能主治】") || str.contains("【适应症】") ||str.contains("【主治功能】")){
                drugVO.setGnzz(str.split("】")[1]);
            }else if(str.contains("【规格】")){
                drugVO.setGg(str.split("】")[1]);
            }else if(str.contains("【用法用量】")){
                drugVO.setYfyl(str.split("】")[1]);
            }else if(str.contains("【执行标准】")){
                drugVO.setZxbz(str.split("】")[1]);
            }else if(str.contains("【批准文号】")){
                drugVO.setPzwh(str.split("】")[1]);
            }

            if(str.contains("OTC") || str.contains("otc") ){
                isCf = 0;
            }
        }
        drugVO.setCfy(isCf);
        if(CollectionUtils.isNotEmpty(medicareDrugDoRepository.findBySpm(drugVO.getMc()))
                || CollectionUtils.isNotEmpty(medicareDrugDoRepository.findByTym(drugVO.getMc()))){
            drugVO.setYb(1);
        }else{
            drugVO.setYb(0);
        }

        if(CollectionUtils.isNotEmpty(substandardDrugDoRepository.findByYpmc(drugVO.getMc()))){
            drugVO.setCfxx(1);
        }else{
            drugVO.setCfxx(0);
        }
        return BaseResult.success(drugVO);
    }

    /*
     * @Author RAICOM2023
     * @Description //快速荐药-根据文本输入框输入的症状信息获得用药方案
     * @Date 8:43 2023/4/29
     * @Param []
     * @return CrossFlowResult
     **/
    @Override
    public BaseResult<MedicationPlanVO2> getMedicationPlan(String sex, String ageGroup, String symptom) throws Exception {
        List<String> symptomWords =  wordFilter.wordList(symptom);

        //若没有匹配到关键词，则返回失败
        if(org.springframework.util.CollectionUtils.isEmpty(symptomWords)){
            return BaseResult.fail(ErrorCodeEnum.MATCH_SYMPTOM_FAIL.getErrorCode(),ErrorCodeEnum.MATCH_SYMPTOM_FAIL.getMsg());
        }
        Integer isFever = 0;
        if(symptomWords.contains("发热") || symptomWords.contains("发烧") || symptomWords.contains("高热")){
            isFever = 1;
        }

        ConcurrentHashMap<String, List<String>> SYMPTOM_DISEASE_MAP = medicineDataCache.get_SYMPTOM_DISEASE_MAP();
        ConcurrentHashMap<String, List<List<String>>> DISEASE_MEDICINE_MAP = medicineDataCache.get_DISEASE_MEDICINE_MAP();
        ConcurrentHashMap<String, DiseaseDo> DISEASE_MAP = medicineDataCache.get_DISEASE_MAP();
        ConcurrentHashMap<String, MedicineDo> MEDICINE_MAP = medicineDataCache.get_MEDICINE_MAP();
        LinkedHashMap<String, Integer> matchDiseaseMap = new LinkedHashMap<>();
        for(String symptomWord : symptomWords){
            if(!SYMPTOM_DISEASE_MAP.containsKey(symptomWord))
                continue;
            for(String diseaseNumber : SYMPTOM_DISEASE_MAP.get(symptomWord)){
                if(matchDiseaseMap.containsKey(diseaseNumber)){
                    matchDiseaseMap.replace(diseaseNumber,matchDiseaseMap.get(diseaseNumber)+1);
                }else{
                    matchDiseaseMap.put(diseaseNumber,1);
                }
            }
        }
        matchDiseaseMap = (LinkedHashMap<String, Integer>) sortMapByValues(matchDiseaseMap);
        if(org.springframework.util.CollectionUtils.isEmpty(matchDiseaseMap)){
            logger.error("快速荐药-根据文本输入框输入的症状信息获得用药方案--症状对应疾病编号为空");
            return BaseResult.fail(ErrorCodeEnum.MD_SYSTEM_ERROR.getErrorCode(),ErrorCodeEnum.MD_SYSTEM_ERROR.getMsg());
        }

        // 最多装三种疾病
        //MedicationPlanVO medicationPlanVO= new MedicationPlanVO();
        MedicationPlanVO2 medicationPlanVO2= new MedicationPlanVO2();
        int n = 0;

        // 本机ip
        InetAddress addr = InetAddress.getLocalHost();

        for(Map.Entry<String, Integer> entry : matchDiseaseMap.entrySet()){
            DiseaseVO diseaseVO = new DiseaseVO();
            String diseaseNumber = entry.getKey();
            DiseaseDo diseaseDo= DISEASE_MAP.get(diseaseNumber);
            List<List<String>> medicinePlanList = DISEASE_MEDICINE_MAP.get(diseaseNumber);
            if(diseaseDo==null || org.springframework.util.CollectionUtils.isEmpty(medicinePlanList)){
                logger.error("快速荐药-根据文本输入框输入的症状信息获得用药方案--根据疾病编号");
                return BaseResult.fail(ErrorCodeEnum.MD_SYSTEM_ERROR.getErrorCode(),ErrorCodeEnum.MD_SYSTEM_ERROR.getMsg());
            }
            int m = 0;
            for(List<String> medicinePlan : medicinePlanList){
                for(String medicineGyzz : medicinePlan){
                    MedicineVO medicineVO = convertMedicineDoTOVo(MEDICINE_MAP.get(medicineGyzz));
                    if(CollectionUtils.isNotEmpty(medicareDrugDoRepository.findBySpm(medicineVO.getChineseName()))
                            || CollectionUtils.isNotEmpty(medicareDrugDoRepository.findByTym(medicineVO.getChineseName()))){
                        medicineVO.setIsYb(1);
                    }else{
                        medicineVO.setIsYb(0);
                    }
                    //medicineVO.setIsYb(1);
                    medicineVO.setPicUrl("http://47.96.4.205:8995/pic/"+medicineVO.getGyzz()+".jpg");
                    //medicineVO.setPicUrl("http://localhost:8995/pic/"+medicineVO.getGyzz()+".jpg");
                    if(m==0){
                        diseaseVO.getMedicationPlanOne().add(medicineVO);
                    }else{
                        diseaseVO.getMedicationPlanTwo().add(medicineVO);
                    }
                }
                m++;
                if(m==2){
                    break;
                }
            }
            diseaseVO.setDiseaseNumber(diseaseNumber);
            diseaseVO.setDiseaseId(diseaseDo.getDiseaseId());
            diseaseVO.setDiseaseName(diseaseDo.getDiseaseName());
            //medicationPlanVO.getDiseaseList().add(diseaseVO);
            medicationPlanVO2.setDiseaseId(diseaseVO.getDiseaseId());
            medicationPlanVO2.setDiseaseName(diseaseVO.getDiseaseName());
            medicationPlanVO2.setDiseaseNumber(diseaseVO.getDiseaseNumber());
            medicationPlanVO2.setMedicationPlanOne(diseaseVO.getMedicationPlanOne());
            medicationPlanVO2.setMedicationPlanTwo(diseaseVO.getMedicationPlanTwo());
            break;
            /*n++;
            if(n==3)
                break;*/
        }
        medicationPlanVO2.setIsFever(isFever);
        return BaseResult.success(medicationPlanVO2);
    }
    /*
     * @Author RAICOM2023
     * @Description //点击下载说明书
     * @Date 8:32 2023/5/5
     * @Param [id]
     * @return com.spire.doc.Document
     **/
    @Override
    public Document downloadDirections(Long id) throws Exception {
        MedicineDo medicineDo = medicineDoRepository.findById(id).get();
        if(medicineDo==null){
            return null;
        }
        //创建Word文档
        Document document = new Document();
        //添加一个section
        Section section = document.addSection();
        Paragraph para1 = section.addParagraph();
        para1.appendText("小易（AI私人医生）");
        Paragraph para2 = section.addParagraph();
        para2.appendText(medicineDo.getChineseName()+"说明书");
        Paragraph para3 = section.addParagraph();
        para3.appendText("____________________________________________________________________________");
        Paragraph para4 = section.addParagraph();
        para4.appendText("请仔细阅读说明书并按说明或在药师指导下购买和使用");

        Paragraph para5 = section.addParagraph();
        para5.appendText("【药物名称】");
        Paragraph para6 = section.addParagraph();
        para6.appendText("通用名称："+medicineDo.getChineseName());
        Paragraph para7 = section.addParagraph();
        para7.appendText("英文名称："+medicineDo.getEnglishName());
        Paragraph para8 = section.addParagraph();
        para8.appendText("汉语拼音："+medicineDo.getPinYin());

        Paragraph para10 = section.addParagraph();
        para10.appendText("【是否处方药】"+medicineDo.getIsRx());

        Paragraph para11 = section.addParagraph();
        para11.appendText("【成份】");
        Paragraph para12 = section.addParagraph();
        para12.appendText(medicineDo.getIngredients());

        Paragraph para13 = section.addParagraph();
        para13.appendText("【性质】");
        Paragraph para14 = section.addParagraph();
        para14.appendText(medicineDo.getCharacter());

        Paragraph para15 = section.addParagraph();
        para15.appendText("【主治功能】");
        Paragraph para16 = section.addParagraph();
        para16.appendText(medicineDo.getFunction());

        Paragraph para17 = section.addParagraph();
        para17.appendText("【用法用量】");
        Paragraph para18 = section.addParagraph();
        para18.appendText(medicineDo.getUsage());

        Paragraph para19 = section.addParagraph();
        para19.appendText("【注意事项】");
        Paragraph para20 = section.addParagraph();
        para20.appendText(medicineDo.getAttention());

        Paragraph para21 = section.addParagraph();
        para21.appendText("【规格】"+medicineDo.getSpecifications());

        Paragraph para22 = section.addParagraph();
        para22.appendText("【禁忌】");
        Paragraph para23 = section.addParagraph();
        para23.appendText(medicineDo.getTaboo());

        Paragraph para24 = section.addParagraph();
        para24.appendText("【相互作用】");
        Paragraph para25 = section.addParagraph();
        para25.appendText(medicineDo.getInteraction());

        Paragraph para26 = section.addParagraph();
        para26.appendText("【不良反应】");
        Paragraph para27 = section.addParagraph();
        para27.appendText(medicineDo.getAdrs());

        Paragraph para28 = section.addParagraph();
        para28.appendText("【执行标准】"+medicineDo.getStandard());

        Paragraph para29 = section.addParagraph();
        para29.appendText("【批准文号】"+medicineDo.getGyzz());

        Paragraph para30 = section.addParagraph();
        para30.appendText("【生产企业】"+medicineDo.getCompany());

        //设置样式
        ParagraphStyle style1 = new ParagraphStyle(document);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);
        style1.getCharacterFormat().setTextColor(Color.BLACK);
        style1.getCharacterFormat().setFontName("宋体");
        style1.getCharacterFormat().setFontSize(20f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        ParagraphStyle style2 = new ParagraphStyle(document);
        style2.setName("titleStyle2");
        style2.getCharacterFormat().setBold(true);
        style2.getCharacterFormat().setTextColor(Color.BLACK);
        style2.getCharacterFormat().setFontName("宋体");
        style2.getCharacterFormat().setFontSize(15f);
        document.getStyles().add(style2);
        para2.applyStyle("titleStyle2");

        ParagraphStyle style3 = new ParagraphStyle(document);
        style3.setName("titleStyle3");
        style3.getCharacterFormat().setBold(true);
        style3.getCharacterFormat().setTextColor(Color.BLACK);
        style3.getCharacterFormat().setFontName("宋体");
        style3.getCharacterFormat().setFontSize(12f);
        document.getStyles().add(style3);
        para3.applyStyle("titleStyle3");
        para4.applyStyle("titleStyle3");

        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        para2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        para3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        para4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        ParagraphStyle style4 = new ParagraphStyle(document);
        style4.setName("paraStyle");
        style4.getCharacterFormat().setFontName("宋体");
        style4.getCharacterFormat().setFontSize(11f);
        document.getStyles().add(style4);
        para5.applyStyle("paraStyle");
        para6.applyStyle("paraStyle");
        para7.applyStyle("paraStyle");
        para8.applyStyle("paraStyle");
        para10.applyStyle("paraStyle");
        para11.applyStyle("paraStyle");
        para12.applyStyle("paraStyle");
        para13.applyStyle("paraStyle");
        para14.applyStyle("paraStyle");
        para15.applyStyle("paraStyle");
        para16.applyStyle("paraStyle");
        para17.applyStyle("paraStyle");
        para18.applyStyle("paraStyle");
        para19.applyStyle("paraStyle");
        para20.applyStyle("paraStyle");
        para21.applyStyle("paraStyle");
        para22.applyStyle("paraStyle");
        para23.applyStyle("paraStyle");
        para24.applyStyle("paraStyle");
        para25.applyStyle("paraStyle");
        para26.applyStyle("paraStyle");
        para27.applyStyle("paraStyle");
        para28.applyStyle("paraStyle");
        para29.applyStyle("paraStyle");
        para30.applyStyle("paraStyle");


        //设置第一段和第二段的段后间距
        para1.getFormat().setBeforeSpacing(20f);
        para1.getFormat().setAfterSpacing(10f);
        para2.getFormat().setAfterSpacing(10f);
        para4.getFormat().setAfterSpacing(10f);

        para6.getFormat().setLeftIndent(30);
        para7.getFormat().setLeftIndent(30);
        para8.getFormat().setLeftIndent(30);
        para12.getFormat().setLeftIndent(30);
        para16.getFormat().setLeftIndent(30);
        para18.getFormat().setLeftIndent(30);
        para20.getFormat().setLeftIndent(30);
        para23.getFormat().setLeftIndent(30);
        para25.getFormat().setLeftIndent(30);
        para27.getFormat().setLeftIndent(30);

        insertTextWatermark(document.getSections().get(0));

        return document;
    }

    /*
     * @Author RAICOM2023
     * @Description //添加水印
     * @Date 9:12 2023/5/5
     * @Param [section]
     * @return void
     **/
    private void insertTextWatermark(Section section) {
        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText("小易（AI私人医生）");
        txtWatermark.setFontSize(40);
        txtWatermark.setColor(Color.red);
        txtWatermark.setLayout(WatermarkLayout.Diagonal);
        section.getDocument().setWatermark(txtWatermark);
    }

    /*
     * @Author RAICOM2023
     * @Description //TODO
     * @Date 19:44 2023/3/6
     * @Param [aMap]
     * @return java.util.Map<K,V>
     **/
    private <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
        HashMap<K, V> finalOut = new LinkedHashMap<>();
        if(!org.springframework.util.CollectionUtils.isEmpty(aMap)){
            aMap.entrySet()
                    .stream()
                    .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                    .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        }
        return finalOut;
    }

    /*
     * @Author RAICOM2023
     * @Description //TODO
     * @Date 19:44 2023/3/6
     * @Param [medicineDo]
     * @return com.hzxy.yiyid.web.module.controller.vo.MedicineVO
     **/
    private MedicineVO convertMedicineDoTOVo(MedicineDo medicineDo){
        MedicineVO medicineVO = new MedicineVO();
        BeanUtils.copyProperties(medicineDo,medicineVO);
        return medicineVO;
    }
}
